package connection;
import java.sql.Connection;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import bean.*;


public class MarketPlaceServer implements MessageListener {

	private javax.jms.Connection connection;
	private Session session;
	private Topic marketTopic;
	private Queue marketQueue;
	private MessageConsumer consumer;
	private MessageConsumer consumerQ;

	

	public DatabaseConnection db = new DatabaseConnection();

	public void sendReply(Message request, String message) {
		try {
			MessageProducer MP = session.createProducer(null);
			Destination reply = request.getJMSReplyTo();
			TextMessage TM = session.createTextMessage();

			TM.setText("" + message); // Change
			MP.send(reply, TM); // Change

		} catch (JMSException JMSE) {
			System.out.println("JMS Exception: " + JMSE);
		}
	}

	public MarketPlaceServer() {
		try {
			Properties properties = new Properties();
			properties.put(Context.INITIAL_CONTEXT_FACTORY,
					"org.jnp.interfaces." + "NamingContextFactory");
			properties.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces");
			properties.put(Context.PROVIDER_URL, "localhost");

			InitialContext jndi = new InitialContext(properties);
			ConnectionFactory conFactory = (ConnectionFactory) jndi
					.lookup("XAConnectionFactory");
			connection = conFactory.createConnection();

			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

			try {
				marketTopic = (Topic) jndi.lookup("MarketTopic");
				marketQueue = (Queue) jndi.lookup("queue/MarketQueue");
			} catch (NamingException NE1) {
				System.out.println("NamingException: " + NE1
						+ " : Continuing anyway...");
			}

			if (null == marketTopic) {
				marketTopic = session.createTopic("MarketTopic");
				jndi.bind("MarketTopic", marketTopic);
			}
			if (null == marketQueue) {
				marketQueue = session.createQueue("queue/MarketQueue");
				jndi.bind("MarketQueue", marketQueue);
			}
			consumer = session.createConsumer(marketTopic);
			consumer.setMessageListener(this);
			consumerQ = session.createConsumer(marketQueue);
			consumerQ.setMessageListener(this);
			System.out.println("Server started waiting for client requests");
			connection.start();
		} catch (NamingException NE) {
			System.out.println("Naming Exception: " + NE);
		} catch (JMSException JMSE) {
			System.out.println("JMS Exception: " + JMSE);
			JMSE.printStackTrace();
		}
	}

	@Override
	public void onMessage(Message message) {

		try
		{
			TextMessage TM = (TextMessage)message;
			StringTokenizer strToken = new StringTokenizer(TM.getText(), "$");
			
			String operation = strToken.nextToken();
			String result = new String();
			String resultArr[];
			
			String emailId; 
			String fName;
			String lName;
			String password;
			if( operation.equals("signUp"))
			{
				emailId = strToken.nextToken();
				fName = strToken.nextToken();
				lName = strToken.nextToken();
				password = strToken.nextToken();
				result = String.valueOf(signUp(emailId, fName, lName, password));
				sendReply(message, result);
			}
			else if( operation.equals("signIn"))
			{
				emailId = strToken.nextToken();
				password = strToken.nextToken();
				signIn(emailId, password);
				result = String.valueOf(signIn(emailId, password));
				sendReply(message, result);
			}
			else if (operation.equals("fetchUserFName"))
			{
				//result = fetchUserFName(strToken.nextToken());
				sendReply(message, result);
			}
			else if (operation.equals("fetchUserFName"))
			{
				//result = fetchUserFName(strToken.nextToken());
				sendReply(message, result);
			}			
			
		}
		catch(JMSException JMSE)
		{
			System.out.println("JMS Exception: "+JMSE);
		}
	}

	public String signUp(String emailId, String password, String firstName, String lastName) {
		String result = null;
		
		//System.out.println("harry1");
		
		result = db.addUser(emailId, password, firstName, lastName);
		
		//result = d
		
		return result;
		
	}
	
	public String signIn(String emailId, String password) {
		String result = null;
		
		result = db.retreiveUser(emailId, password);
		
		return result;
		
	}
	
	public String addAdvertisement(String userId, String itemName, String itemDescription, String itemPrice, String itemQuantity, String sellerInfo) {
		
		String result = null;
		
		result = db.addAdvertisement(userId, itemName, itemDescription,itemPrice,itemQuantity,sellerInfo);
		
		return result;
	}
	
	public Advertisement[] getMyAdvertisement(String userId) {
		
		//String result = null;
		ArrayList<Advertisement> alAdvert = new ArrayList<Advertisement>();
		
		//Advertisement oAdvert = new Advertisement();
		
		alAdvert = db.fetchAdvertisementById(userId);
		
		Advertisement aoAdvert[] = new Advertisement[alAdvert.size()];
		
		Iterator<Advertisement> itr = alAdvert.iterator(); 
		int i=0;
		while(itr.hasNext()) {
			aoAdvert[i] = (Advertisement)itr.next();
			System.out.println(aoAdvert[i].getItemName());
			i++;
		}
		
		System.out.println(alAdvert.size());
		//result = db.fetchAdvertisementById(userId);
		
		return aoAdvert;
		
	}
	
	public Advertisement[] getOtherAdvertisement(String userId) {
		
		//String result = null;
		ArrayList<Advertisement> alAdvert = new ArrayList<Advertisement>();
		
		//Advertisement oAdvert = new Advertisement();
		
		alAdvert = db.fetchAdvertisementExcludingId(userId);
		
		Advertisement aoAdvert[] = new Advertisement[alAdvert.size()];
		
		Iterator<Advertisement> itr = alAdvert.iterator(); 
		int i=0;
		while(itr.hasNext()) {
			aoAdvert[i] = (Advertisement)itr.next();
			System.out.println(aoAdvert[i].getItemName());
			i++;
		}
		
		System.out.println(alAdvert.size());
		//result = db.fetchAdvertisementById(userId);
		
		return aoAdvert;
		
	}
	
	public String addItemToCart(String userId,String itemId, String itemQuantity) {
		
		String result = null;
		result = db.insertCartItem(userId,itemId,itemQuantity);
		
		return result;
		
	}
	
	public CartItem[] getUserCart(String userId) {
		
		ArrayList<CartItem> alCartItem = new ArrayList<CartItem>();
		
		//Advertisement oAdvert = new Advertisement();
		
		alCartItem = db.fetchUserCart(userId);
		
		CartItem aoCartItem[] = new CartItem[alCartItem.size()];
		
		Iterator<CartItem> itr = alCartItem.iterator(); 
		int i=0;
		while(itr.hasNext()) {
			aoCartItem[i] = (CartItem)itr.next();
			//System.out.println(aoCartItem[i].getItemName());
			i++;
		}
		
		System.out.println(alCartItem.size());
		//result = db.fetchAdvertisementById(userId);
		
		return aoCartItem;
		
	}
	
	public String updateItemInCart(String cartItemId, String orderedQuantity) {
		String result = null;
		
		result = db.updateCartItem(cartItemId,orderedQuantity);
		
		return result;
	}
	
	public Advertisement[] getUserCartItemDetails(String userId) {
		
		ArrayList<Advertisement> alAdvert = new ArrayList<Advertisement>();
		
		//Advertisement oAdvert = new Advertisement();
		
		alAdvert = db.fetchAdvertisementDetailsOfCartItems(userId);
		
		Advertisement aoAdvert[] = new Advertisement[alAdvert.size()];
		
		Iterator<Advertisement> itr = alAdvert.iterator(); 
		int i=0;
		while(itr.hasNext()) {
			aoAdvert[i] = (Advertisement)itr.next();
			System.out.println(aoAdvert[i].getItemName());
			i++;
		}
		
		System.out.println(alAdvert.size());
		//result = db.fetchAdvertisementById(userId);
		
		return aoAdvert;
	}
	
	public String deleteItemInCart(String cartItemId) {
		String result = null;
		
		result = db.deleteItemInCart(cartItemId);
		
		return result;
		
	}
	
	public String checkAvailableQuantityForItemsInCart(String userId) {
		
		String result = null;
		
		result = db.checkAvailableQuantityForItemsInCart(userId);
		
		return result;
		
	}
	
	public String purchaseItemsInCart(String userId) {
		String result = "false";
		
		result = db.purchaseItemsInCart(userId);
		return result;
	}
	
	public TransactedItem[] getPurchasedItems(String userId) {
		
		ArrayList<TransactedItem> alTransactedItem = new ArrayList<TransactedItem>();
		
		
		alTransactedItem = db.getPurchasedItems(userId);
		
		TransactedItem aoTransactedItem[] = new TransactedItem[alTransactedItem.size()];
		
		Iterator<TransactedItem> itr = alTransactedItem.iterator(); 
		int i=0;
		while(itr.hasNext()) {
			aoTransactedItem[i] = (TransactedItem)itr.next();
			//System.out.println(aoTransactedItem[i].getItemName());
			i++;
		}
		
		System.out.println(alTransactedItem.size());
		//result = db.fetchAdvertisementById(userId);
		//aoTransactedItem.toString()
		return aoTransactedItem;
	}
	public TransactedItem[] getSoldItems(String userId) {
		
		ArrayList<TransactedItem> alTransactedItem = new ArrayList<TransactedItem>();
		
		
		alTransactedItem = db.getSoldItems(userId);
		
		TransactedItem aoTransactedItem[] = new TransactedItem[alTransactedItem.size()];
		
		Iterator<TransactedItem> itr = alTransactedItem.iterator(); 
		int i=0;
		while(itr.hasNext()) {
			aoTransactedItem[i] = (TransactedItem)itr.next();
			//System.out.println(aoTransactedItem[i].getItemName());
			i++;
		}
		
		System.out.println(alTransactedItem.size());
		//result = db.fetchAdvertisementById(userId);
		
		return aoTransactedItem;
	}
	
	public Advertisement[] getOtherAdvertisementExcludingId(String userId) {
		
		//String result = null;
		ArrayList<Advertisement> alAdvert = new ArrayList<Advertisement>();
		
		//Advertisement oAdvert = new Advertisement();
		
		alAdvert = db.getOtherAdvertisementExcludingId(userId);
		
		Advertisement aoAdvert[] = new Advertisement[alAdvert.size()];
		
		Iterator<Advertisement> itr = alAdvert.iterator(); 
		int i=0;
		while(itr.hasNext()) {
			aoAdvert[i] = (Advertisement)itr.next();
			System.out.println(aoAdvert[i].getItemName());
			i++;
		}
		
		System.out.println(alAdvert.size());
		//result = db.fetchAdvertisementById(userId);
		
		return aoAdvert;
		
	}
	
	public String updateMyAdvertisement(String itemId,String itemQuantity) {
		
		String result = "false";
		
		result = db.updateMyAdvertisement(itemId,itemQuantity);
		
		return result;
	}
	
	public String deleteMyAdvertisement(String itemId) {
		
		String result = null;
		
		result = db.deleteMyAdvertisement(itemId);
		
		return result;
	}
}
